package test.algorithm.dp;

/**
 * @Projectname: leetCode
 * @Filename: LongestPalindromeString
 * @Author: FANSEA
 * @Date:2024/9/11 20:57
 */

public class LongestPalindromeString {
    public static void main(String[] args) {
        LongestPalindromeString longestPalindromeString = new LongestPalindromeString();
        System.out.println(longestPalindromeString.longestPalindrome("dbabdadad"));
        System.out.println(longestPalindromeString.longestPalindrome("abba"));
        System.out.println(longestPalindromeString.longestPalindrome("bb"));
    }

    // [5.最长回文子串](https://leetcode.cn/problems/longest-palindromic-substring/)
    public String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2) {
            return s;
        }

        int maxLen = 1;
        int begin = 0;
        // dp[i][j] 表示 s[i..j] 是否是回文串
        boolean[][] dp = new boolean[len][len];
        // 初始化：所有长度为 1 的子串都是回文串
        for (int i=0; i<len; i++) {
            dp[i][i] = true;
        }
        char[] charArray = s.toCharArray();
        // 递推开始
        // 先枚举子串长度
        for (int L = 2; L <= len; L++) {
            for (int i = 0; i < len; i++) {
                int j = L + i - 1;
                if (j >= len) {
                    break;
                }
                // 只确定外围的两个字符相同，还不能确定是否是回文
                if(charArray[i] != charArray[j]){
                    dp[i][j] = false;
                } else{
                    // 长度小于等于三就不用看子回文字符串了，外围是否回文就决定了整体是否是回文
                    if(L <= 3){
                        dp[i][j] = true;
                    }
                    else{
                        dp[i][j] = dp[i+1][j-1];
                    }
                }
                if (dp[i][j] && L > maxLen) {
                    maxLen = L;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }
}
